package com.ruicar.afs.cloud.apply.admin.manage.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.admin.condition.RoleCondition;
import com.ruicar.afs.cloud.apply.admin.auth.util.DataAccessUtil;
import com.ruicar.afs.cloud.apply.admin.manage.entity.SysRole;
import com.ruicar.afs.cloud.apply.admin.manage.entity.SysRolePermission;
import com.ruicar.afs.cloud.apply.admin.manage.entity.SysUserPower;
import com.ruicar.afs.cloud.apply.admin.manage.service.ApplyRolePermissionService;
import com.ruicar.afs.cloud.apply.admin.manage.service.ApplyRoleService;
import com.ruicar.afs.cloud.apply.admin.manage.service.SysUserPowerService;
import com.ruicar.afs.cloud.apply.admin.manage.vo.SysRoleVo;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.apply.enums.RoleEnum;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.security.core.userdetails.User;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * @author: Lee
 * @date: 2020/5/11 19:39
 * @description:
 */
@RestController
@AllArgsConstructor
@RequestMapping("/applyRole")
public class ApplyRoleController {

    private ApplyRoleService applyRoleService;
    private ApplyRolePermissionService applyRolePermissionService;
    private SysUserPowerService sysUserPowerService;

    @PostMapping("/getAllList")
    @ApiOperation(value = "查询角色")
    public IResponse getAllList(@RequestParam(name = "businessType", required = false) String businessType) {
        List<SysRole> list = applyRoleService.list(Wrappers.<SysRole>query().lambda().like(StringUtils.isNotEmpty(businessType), SysRole::getRoleType, businessType));
        List<String> roleCodeList = SecurityUtils.getUser().getRoleCodeList();
        //非超级管理员用户，不展示渠道角色和超级管理员角色
        if (DataAccessUtil.isAdmin()) {
            Iterator<SysRole> it = list.iterator();
            while (it.hasNext()) {
                String roleCode = it.next().getRoleCode();
                if (roleCode.equals(RoleEnum.ROLE_ADMIN.name())) {
                    it.remove();
                }
            }
        }
        return new IResponse().setData(list);
    }

    @PostMapping("/getCommissionLoan")
    @ApiOperation(value = "查询佣金和贷后")
    public IResponse getCommissionLoan() {
        List<SysRole> list = applyRoleService.list(Wrappers.<SysRole>query().lambda().in(SysRole::getRoleCode, RoleEnum.ROLE_COMMISSION.name(), RoleEnum.ROLE_LOANAFTER.name()).orderByAsc(SysRole::getCreateTime));
        return new IResponse().setData(list);
    }


    @PostMapping("/getApplyAllList")
    @ApiOperation(value = "查询渠道使用的角色")
    public IResponse getApplyAllList(@RequestParam(name = "businessType", required = false) String businessType) {
        List<SysRole> list = applyRoleService.list(Wrappers.<SysRole>query().lambda().like(StringUtils.isNotEmpty(businessType), SysRole::getRoleType, businessType).in(SysRole::getRoleCode, RoleEnum.ROLE_PREPAYMENT.name(), RoleEnum.ROLE_PAYMENT.name(), RoleEnum.ROLE_COMMISSION.name(), RoleEnum.ROLE_LOANAFTER.name(), RoleEnum.ROLE_RECORDED.name(), RoleEnum.ROLE_APPLY.name(), RoleEnum.ROLE_XCRECORDED.name(), RoleEnum.ROLE_XCPAYMENT.name(), RoleEnum.ROLE_XCPREPAYMENT.name(), RoleEnum.ROLE_XCAPPLY.name()).orderByAsc(SysRole::getCreateTime));
        return new IResponse().setData(list);
    }

    @PostMapping("/getMatchingRole")
    @ApiOperation(value = "获取只有新车或者二手车的角色")
    public IResponse getMatchingRole(@RequestParam(name = "businessType", required = false) String businessType) {
        List<SysRole> list = applyRoleService.list(Wrappers.<SysRole>query().lambda().eq(StringUtils.isNotEmpty(businessType), SysRole::getRoleType, businessType).in(SysRole::getRoleCode, RoleEnum.ROLE_PREPAYMENT.name(), RoleEnum.ROLE_PAYMENT.name(), RoleEnum.ROLE_COMMISSION.name(), RoleEnum.ROLE_LOANAFTER.name(), RoleEnum.ROLE_RECORDED.name(), RoleEnum.ROLE_APPLY.name(), RoleEnum.ROLE_XCRECORDED.name(), RoleEnum.ROLE_XCPAYMENT.name(), RoleEnum.ROLE_XCPREPAYMENT.name(), RoleEnum.ROLE_XCAPPLY.name()).orderByAsc(SysRole::getCreateTime));
        List<String> roleCodeList = SecurityUtils.getUser().getRoleCodeList();
        //非超级管理员用户，不展示渠道角色和超级管理员角色
        if (DataAccessUtil.isAdmin()) {
            Iterator<SysRole> it = list.iterator();
            while (it.hasNext()) {
                String roleCode = it.next().getRoleCode();
                if (roleCode.equals(RoleEnum.ROLE_ADMIN.name())) {
                    it.remove();
                }
            }
        }
        return new IResponse().setData(list);
    }

    @PostMapping(value = "/getAllByPage")
    @ApiOperation(value = "分页获取角色")
    public IResponse getRoleByPage(@RequestParam(name = "pageNumber") int pageNumber, @RequestParam(name = "pageSize") int pageSize) {
        IPage<SysRole> list = applyRoleService.page(new Page(pageNumber, pageSize));
        for (SysRole role : list.getRecords()) {
            // 角色拥有权限
            List<SysRolePermission> permissions = applyRolePermissionService.list(Wrappers.<SysRolePermission>query().lambda().eq(SysRolePermission::getRoleId, role.getId()));
            role.setPermissions(permissions);
        }
        return new IResponse().setData(list);
    }

    @PostMapping("/add")
    @ApiOperation(value = "新增角色")
    @CacheEvict(value = CommonConstants.USER_CACHE_KEY_PREFIX, allEntries = true)
    public IResponse add(@RequestBody SysRole channelRole) {
        applyRoleService.save(channelRole);
        return new IResponse().setMsg("角色新增成功").setData(true);
    }

    @PostMapping("/edit")
    @ApiOperation(value = "编辑角色")
    @CacheEvict(value = CommonConstants.USER_CACHE_KEY_PREFIX, allEntries = true)
    public IResponse edit(@RequestBody SysRole role) {
        applyRoleService.updateById(role);
        return new IResponse().setMsg("角色编辑成功").setData(true);
    }

    @DeleteMapping("/delAllByIds/{ids}")
    @ApiOperation(value = "删除角色")
    @CacheEvict(value = CommonConstants.USER_CACHE_KEY_PREFIX, allEntries = true)
    public IResponse delAllByIds(@PathVariable Long[] ids) {
        applyRoleService.removeByIds(Arrays.asList(ids));
        return new IResponse().setMsg("角色删除成功").setData(true);
    }

    @RequestMapping(value = "/editRolePerm", method = RequestMethod.POST)
    @ApiOperation(value = "编辑角色分配菜单权限")
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = CommonConstants.USER_CACHE_KEY_PREFIX, allEntries = true)
    public IResponse<Boolean> editRolePerm(@RequestBody RoleCondition roleCondition) {

        //删除其关联权限
        applyRolePermissionService.remove(Wrappers.<SysRolePermission>update().lambda().eq(SysRolePermission::getRoleId, roleCondition.getRoleId()));
        //分配新权限
        for (String permId : roleCondition.getPermIds()) {
            SysRolePermission rolePermission = new SysRolePermission();
            rolePermission.setRoleId(roleCondition.getRoleId());
            rolePermission.setPermissionId(permId);
            applyRolePermissionService.save(rolePermission);
        }
        return new IResponse<Boolean>().setMsg("保存成功").setData(true);
    }


    @PostMapping("/getUserRole")
    @ApiOperation(value = "获取所有角色对应的角色")
    public IResponse getUserRole() {
        JSONObject user = SecurityUtils.getUser().getUserExtInfo();
        String channel = user.get("channelId").toString();
        Long channelId = Long.valueOf(channel);
        List<SysRoleVo> roles = applyRoleService.getUserRole(channelId);
        return new IResponse().setData(roles);
    }


    @PostMapping(value = "/getAllRoleByRoleType")
    @ApiOperation(value = "根据当前登录人权限获取对应角色")
    public IResponse getAllRoleByRoleType(@RequestParam(name = "pageNumber") int pageNumber, @RequestParam(name = "pageSize") int pageSize,@RequestParam(name = "roleType") String roleType) {
        IPage<SysRole> list = applyRoleService.page(new Page(pageNumber, pageSize),Wrappers.<SysRole>query().lambda()
                .like(StringUtils.isNotEmpty(roleType),SysRole::getRoleType,roleType));
        for (SysRole role : list.getRecords()) {
            // 角色拥有权限
            List<SysRolePermission> permissions = applyRolePermissionService.list(Wrappers.<SysRolePermission>query().lambda().eq(SysRolePermission::getRoleId, role.getId()));
            role.setPermissions(permissions);
        }
        return new IResponse().setData(list);
    }

    @PostMapping("/getApplyRoleByType")
    @ApiOperation(value = "根据类型获取角色信息")
    public IResponse getApplyRoleByType(@RequestBody String businessType) {
        List<SysRole> list = applyRoleService.list(Wrappers.<SysRole>query().lambda().like(StringUtils.isNotEmpty(businessType), SysRole::getRoleType, businessType).in(SysRole::getRoleCode, RoleEnum.ROLE_PREPAYMENT.name(), RoleEnum.ROLE_PAYMENT.name(), RoleEnum.ROLE_COMMISSION.name(), RoleEnum.ROLE_LOANAFTER.name(), RoleEnum.ROLE_RECORDED.name(), RoleEnum.ROLE_APPLY.name(), RoleEnum.ROLE_XCRECORDED.name(), RoleEnum.ROLE_XCPAYMENT.name(), RoleEnum.ROLE_XCPREPAYMENT.name(), RoleEnum.ROLE_XCAPPLY.name()).orderByAsc(SysRole::getCreateTime));
        return new IResponse().setData(list);
    }

    @PostMapping("/getUserPower")
    @ApiOperation(value = "根据获取登录用户的权限")
    public IResponse getUserPower() {
        SysUserPower power =sysUserPowerService.getOne(Wrappers.<SysUserPower>query().lambda().eq(SysUserPower::getUserId,SecurityUtils.getUser().getId()));

        return new IResponse().setData(power);
    }

}
